<template>
  <div>
    <el-dialog
      v-el-drag-dialog
      :title="!dataForm.id ? '新增' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @submit.native.prevent="dataFormSubmit()" label-width="80px">
        <el-form-item label="专题名称" prop="floorName">
          <el-input v-model="dataForm.floorName"  placeholder="专题名称只做为内部标识"></el-input>
        </el-form-item>
        <el-form-item label="副标题" prop="description">
          <el-input v-model="dataForm.description"  placeholder="副标题"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="bigImg">
          <el-upload
            class="avatar-uploader"
            :action="this.$http.adornUrl(`/banner/uploadBanner?token=${this.$cookie.get('token')}`)"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="dataForm.bigImg" :src="dataForm.bigImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="小图标" prop="specialSmallImg">
          <el-upload
            class="avatar-uploader"
            :action="this.$http.adornUrl(`/banner/uploadBanner?token=${this.$cookie.get('token')}`)"
            :show-file-list="false"
            :on-success="handleAvatarSuccess1"
            :before-upload="beforeAvatarUpload">
            <img v-if="dataForm.specialSmallImg" :src="dataForm.specialSmallImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="平台类型" prop="appType" v-show="!dataForm.id">
          <el-radio v-model="dataForm.appType" label="1">安卓</el-radio>
          <el-radio v-model="dataForm.appType" label="2">苹果</el-radio>
          <el-radio v-model="dataForm.appType" label="3">小程序</el-radio>
          <el-radio v-model="dataForm.appType" label="0">全部</el-radio>
        </el-form-item>
        <el-form-item label="选择商品">
          <el-button @click="addOrUpdateHandle">选择商品</el-button>
          <el-table v-if="goodsList.length !== 0"
            :data="goodsInfoList"
            height="300"
            border
            style="width: 100%">
            <el-table-column
              prop="img"
              label="商品图">
              <template slot-scope="scope">
                <el-popover
                  placement="right"
                  trigger="hover">
                  <img :src="scope.row.img" style="max-height: 100px;"/>
                  <img slot="reference" :src="scope.row.img" style="max-height: 50px;max-width: 130px">
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column
              prop="goodsName"
              show-overflow-tooltip
              label="商品名">
            </el-table-column>
            <!-- <el-table-column
              prop="address"
              label="价格类型">
              <template slot-scope="scope">
                {{scope.row.address === 1 ?'兑换商城':'福利商城'}}
              </template>
            </el-table-column> -->
            <el-table-column
              prop="goodsInventory"
              label="库存">
            </el-table-column>
            <el-table-column
              header-align="center"
              align="center"
              label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small" v-if="isAuth('home:floor:remove')"  @click="deleteGoodsHandle(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="排序" prop="seq">
          <el-input v-model="dataForm.seq" placeholder="数值越大排序越靠前"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dataForm.remark"  type="textarea" placeholder="备注"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>

    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @getGoodsList="getGoodsList"></add-or-update>
  </div>
</template>

<script>
  import AddOrUpdate from './special-goods'
  export default {
    data () {
      return {
        visible: false,
        dialogImageUrl: '',
        dialogVisible: false,
        addOrUpdateVisible: false,
        goodsList: [],
        goodsInfoList: [],
        dataForm: {
          id: 0,
          remark: '',
          floorName: '',
          seq: 0,
          description: '',
          specialSmallImg: '',
          bigImg: '',
          appType: '0'
        },
        dataRule: {}
      }
    },
    components: {
      AddOrUpdate
    },
    methods: {
      handleAvatarSuccess (res, file) {
        this.dataForm.bigImg = res.data
      },
      beforeAvatarUpload (file) {
        console.log(file)
        const isJPG = file.type === 'image/jpeg' || 'image/png'
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        return isJPG
      },
      handleAvatarSuccess1 (res, file) {
        this.dataForm.specialSmallImg = res.data
      },
      getGoodsList (goodsList, goodsInfoList) {
        this.goodsList = goodsList
        this.goodsInfoList = goodsInfoList
      },
      init (id) {
        Object.assign(this.$data, this.$options.data())
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/special/getGoodsRecommendInfoById/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.remark = data.data.remark
                this.dataForm.floorName = data.data.floorName
                this.dataForm.description = data.data.description
                this.dataForm.specialSmallImg = data.data.specialSmallImg != null ? 'https://image.yilianbaihui.cn/consumer/' + data.data.specialSmallImg : ''
                this.dataForm.bigImg = data.data.imgName != null ? 'https://image.yilianbaihui.cn/consumer/' + data.data.imgPath + '/' + data.data.imgName : ''
                this.goodsList = []
                this.goodsInfoList = []
                let than = this
                data.data.urlData.split(',').map(
                  item => {
                    let id = Number.parseInt(item)
                    if (Number.isInteger(id)) {
                      this.getGoods(id).then(data => {
                        than.goodsList.push(id)
                        than.goodsInfoList.push({
                          'img': data.img,
                          'id': data.id,
                          'goodsName': data.goodsName,
                          'priceType': data.priceType,
                          'goodsInventory': data.goodsInventory
                        })
                      })
                    }
                  })
                this.dataForm.seq = data.data.seq
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit: function () {
        if (this.dataForm.bigImg !== '') {
          let index = this.dataForm.bigImg.lastIndexOf('\/')
          this.dataForm.bigImg  = this.dataForm.bigImg.substring(index + 1, this.dataForm.bigImg.length)
        } else {
          this.$message.error('请上传图标！')
          return
        }
        if (this.dataForm.specialSmallImg !== '') {
          let index = this.dataForm.specialSmallImg.lastIndexOf('\/')
          this.dataForm.specialSmallImg  = 'banner/' + this.dataForm.specialSmallImg.substring(index + 1, this.dataForm.specialSmallImg.length)
        } else {
          this.$message.error('请上传小图标！')
          return
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/special/${!this.dataForm.id ? 'addGoodsCommend' : 'modifyGoodsRecommendDetailsById'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'floorName': this.dataForm.floorName,
                'seq': this.dataForm.seq,
                'urlData': this.goodsList.join(','),
                'remark': this.dataForm.remark,
                'imgPath': this.dataForm.bigImg !== '' ? 'banner' : '',
                'imgName': this.dataForm.bigImg,
                'specialSmallImg': this.dataForm.specialSmallImg,
                'description': this.dataForm.description,
                'appType': this.dataForm.appType
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(this.dataForm.id, this.goodsList, this.goodsInfoList)
        })
      },
      deleteGoodsHandle (id) {
        this.goodsList.splice(this.goodsList.indexOf(id), 1)
        for (let i = 0; i < this.goodsInfoList.length; i++) {
          if (this.goodsInfoList[i].id === id) {
            this.goodsInfoList.splice(i, 1)
            i--
          }
        }
      },
      async getGoods (id) {
        let info
        try {
          await this.$http({
            url: this.$http.adornUrl(`/goods/getGoodsById/${id}`),
            method: 'post'
          }).then(({data}) => {
            if (data && data.code === 0) {
              info = data.data
            }
          })
        } catch (e) {
          console.log(e)
        }
        return info
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
  }
  .avatar {
    width: 128px;
    height: 128px;
    display: block;
  }
</style>
